package com.chennan.redis.domain.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @author chennan
 * @createTime 2021年07月23日 11:05:00
 */
@Service
public class RedisService {

    @Resource(name = "stringRedisTemplate")
//    @Autowired
//    @Qualifier(value = "stringRedisTemplate")
    private ValueOperations<String, String> redisValueOps;

    @Autowired
    private RedisTemplate<String, ?> redisTemplate;


    /**
     * 简单实现
     * @param key
     * @param value
     * @param time
     * @return
     */
    public Boolean simpleSetNX(String key, String value, int time, TimeUnit timeUnit){
        //先进行获取key，如果没有则进行设置
        String s = redisValueOps.get(key);
        if(StringUtils.isEmpty(s)){
            redisValueOps.set(key,value,time,timeUnit);
            return true;
        }
        return false;
    }

    /**
     *  调用nx原生方法进行设置
     *
     */
    public Boolean setNX(String key, String value, int time, TimeUnit timeUnit){
        Boolean execute = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = RedisService.this.redisTemplate.getStringSerializer();
                Boolean result = connection.set(serializer.serialize(key), serializer.serialize(value), Expiration.from(time,timeUnit), RedisStringCommands.SetOption.SET_IF_ABSENT);
                return result == null ? false : result;
            }
        });
        return execute;
    }

    public Long incr(String key,Long stepSize){
        Long increment = redisValueOps.increment(key, stepSize);
        return increment;
    }

}
